package com.quickly.develop.common.handler;

import java.util.ArrayList;
import java.util.List;

import com.quickly.develop.common.base.BaseEntity;
import com.quickly.develop.common.entity.PageRequest;
import com.quickly.develop.common.entity.PageResponse;

/**
 * 分页查询处理器
 *
 */

public class PageHandler<T extends BaseEntity> {

	private CountHandler<T> countHandler;
	private ListHandler<T> listHandler;
	private OrderHandler<T> orderHandler;

	public PageHandler(CountHandler<T> countHandler, ListHandler<T> listHandler) {
		super();
		this.countHandler = countHandler;
		this.listHandler = listHandler;
	}

	public PageHandler(CountHandler<T> countHandler, ListHandler<T> listHandler, OrderHandler<T> orderHandler) {
		this(countHandler, listHandler);
		this.orderHandler = orderHandler;
	}

	public PageResponse<T> handle(PageRequest<T> dtRequest) {
		int count = 0;
		List<T> list = new ArrayList<T>();

		count = this.countHandler.count(dtRequest);
		if (count > 0) {
			if (orderHandler != null) {
				dtRequest = orderHandler.order(dtRequest);
			}
			list =  this.listHandler.list(dtRequest);
		}

		if (list == null) {
			list = new ArrayList<>();
		}
		PageResponse<T> pageResponse=new PageResponse<T>();
		pageResponse.setCount(count);
		pageResponse.setData(list);
		return pageResponse;
	}

	public interface ListHandler<T extends BaseEntity> {
		List<T> list(PageRequest<T> request);
	}

	public interface CountHandler<T extends BaseEntity> {
		int count(PageRequest<T> request);
	}

	public interface OrderHandler<T extends BaseEntity> {
		PageRequest<T> order(PageRequest<T> request);
	}
}